{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 字符串操作"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "首先回归一下python字符串的相关操作，这是非常基础的知识，但却是使用频度非常高的一些功能。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 去空格及特殊符号"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "hello, world!\n",
      "world!\n",
      " hello, world\n"
     ]
    }
   ],
   "source": [
    "s = ' hello, world!'\n",
    "print(s.strip())\n",
    "print(s.lstrip('hello, '))\n",
    "print(s.rstrip('!'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 连接字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "strcatappend\n"
     ]
    }
   ],
   "source": [
    "sStr1 = 'strcat'\n",
    "sStr2 = 'append'\n",
    "sStr1 += sStr2\n",
    "print(sStr1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 查找字符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "# < 0 为未找到\n",
    "sStr1 = 'strchr'\n",
    "sStr2 = 'r'\n",
    "nPos = sStr1.index(sStr2)\n",
    "print(nPos)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 比较字符串\n",
    "- python3移除了cmp()函数，但提供了六个丰富的比较运算符"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "True"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import operator       #首先要导入运算符模块\n",
    "operator.gt(1,2)      #意思是greater than（大于）\n",
    "operator.ge(1,2)      #意思是greater and equal（大于等于）\n",
    "operator.eq(1,2)      #意思是equal（等于）\n",
    "operator.le(1,2)      #意思是less and equal（小于等于）\n",
    "operator.lt(1,2)      #意思是less than（小于）"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 字符串中的大小写转换"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "JCSTRLWR\n"
     ]
    }
   ],
   "source": [
    "sStr1 = 'JCstrlwr'\n",
    "sStr1 = sStr1.upper()\n",
    "#sStr1 = sStr1.lower()\n",
    "print(sStr1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 翻转字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "gfedcba\n"
     ]
    }
   ],
   "source": [
    "sStr1 = 'abcdefg'\n",
    "sStr1 = sStr1[::-1]\n",
    "print(sStr1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 查找字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "2\n"
     ]
    }
   ],
   "source": [
    "sStr1 = 'abcdefg'\n",
    "sStr2 = 'cde'\n",
    "print(sStr1.find(sStr2))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 分割字符串"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "cde,fgh,ijk\n",
      "['ab', 'cde', 'fgh', 'ijk']\n"
     ]
    }
   ],
   "source": [
    "sStr1 = 'ab,cde,fgh,ijk'\n",
    "sStr2 = ','\n",
    "sStr1 = sStr1[sStr1.find(sStr2) + 1:]\n",
    "print(sStr1)\n",
    "\n",
    "#或者\n",
    "s = 'ab,cde,fgh,ijk'\n",
    "print(s.split(','))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 计算字符串中出现频次最多的字母"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [],
   "source": [
    "#version 1\n",
    "import re #正则表达式的介绍见后文\n",
    "from collections import Counter\n",
    "\n",
    "def get_max_value1(text):\n",
    "    text = text.lower()\n",
    "    result = re.findall('[a-zA-Z]', text)  # 去掉列表中的符号符\n",
    "    count = Counter(result)  # Counter({'l': 3, 'o': 2, 'd': 1, 'h': 1, 'r': 1, 'e': 1, 'w': 1})\n",
    "    count_list = list(count.values())\n",
    "    max_value = max(count_list)\n",
    "    max_list = []\n",
    "    for k, v in count.items():\n",
    "        if v == max_value:\n",
    "            max_list.append(k)\n",
    "    max_list = sorted(max_list)\n",
    "    return max_list[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [],
   "source": [
    "#version 2\n",
    "from collections import Counter\n",
    "\n",
    "def get_max_value2(text):\n",
    "    count = Counter([x for x in text.lower() if x.isalpha()])\n",
    "    m = max(count.values())\n",
    "    return sorted([x for (x, y) in count.items() if y == m])[0]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [],
   "source": [
    "#version 3\n",
    "import string\n",
    "\n",
    "def get_max_value3(text):\n",
    "    text = text.lower()\n",
    "    return max(string.ascii_lowercase, key=text.count)  #string.ascii_lowercase获取所有ascii码中的小写英文字母"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Two Apples', 'A lovely little girl was holding two apples with both hands.', 'Her mum came in and softly asked her little daughter with a smile:\"my sweetie, could you give your mum one of your two apples? \"', 'The girl looked up at her mum for some seconds, then she suddenly took a quick bite on one apple, and then quickly on the other.', 'The mum felt the smile on her face freeze. She tried hard not to reveal her disappointment.', 'Then the little girl handed one of her bitten apples to her mum,and said:\"mummy, here you are. This is the sweeter one. \"', 'No matter who you are, how experienced you are, and how knowledgeable you', 'think you are, always delay judgement.', 'Give others the privilege to explain themselves.', 'What you see may not be the reality. Never conclude for others.', 'Which is why we should never only focus on the surface and judge others', 'without understanding them first.']\n",
      "Two Apples,A lovely little girl was holding two apples with both hands.,Her mum came in and softly asked her little daughter with a smile:\"my sweetie, could you give your mum one of your two apples? \",The girl looked up at her mum for some seconds, then she suddenly took a quick bite on one apple, and then quickly on the other.,The mum felt the smile on her face freeze. She tried hard not to reveal her disappointment.,Then the little girl handed one of her bitten apples to her mum,and said:\"mummy, here you are. This is the sweeter one. \",No matter who you are, how experienced you are, and how knowledgeable you,think you are, always delay judgement.,Give others the privilege to explain themselves.,What you see may not be the reality. Never conclude for others.,Which is why we should never only focus on the surface and judge others,without understanding them first.\n"
     ]
    }
   ],
   "source": [
    "f=open('C:/Users/灬月光皆旧梦/Desktop/Python-NLP/datas/短文.txt', encoding='gbk')\n",
    "txt=[]\n",
    "for line in f:\n",
    "    txt.append(line.strip())\n",
    "\n",
    "str1 = \",\".join(txt)\n",
    "print(txt)\n",
    "print(str1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "e\n",
      "e\n",
      "e\n"
     ]
    }
   ],
   "source": [
    "print(get_max_value1(str1))\n",
    "print(get_max_value2(str1)) \n",
    "print(get_max_value3(str1)) "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### 关于max"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "3\n",
      "5\n",
      "ah\n",
      "bf\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "'l'"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "max(range(6), key = lambda x : x>2)\n",
    "# >>> 3\n",
    "# 带入key函数中，各个元素返回布尔值，相当于[False, False, False, True, True, True]\n",
    "# key函数要求返回值为True，有多个符合的值，则挑选第一个。\n",
    "print(max(range(6), key = lambda x : x>2))\n",
    "\n",
    "max([3,5,2,1,4,3,0], key = lambda x : x)\n",
    "# >>> 5\n",
    "# 带入key函数中，各个元素返回自身的值，最大的值为5，返回5.\n",
    "print(max([3,5,2,1,4,3,0], key = lambda x : x))\n",
    "\n",
    "\n",
    "max('ah', 'bf', key=lambda x: x[1])\n",
    "# >>> 'ah'\n",
    "# 带入key函数，各个字符串返回最后一个字符，其中'ah'的h要大于'bf'中的f，因此返回'ah'\n",
    "print(max('ah', 'bf', key=lambda x: x[1]))\n",
    "\n",
    "\n",
    "max('ah', 'bf', key=lambda x: x[0])\n",
    "# >>> 'bf'\n",
    "# 带入key函数，各个字符串返回第一个字符，其中'bf'的b要大于'ah'中的a，因此返回'bf'\n",
    "print(max('ah', 'bf', key=lambda x: x[0]))\n",
    "\n",
    "text = 'Hello World'\n",
    "max('abcdefghijklmnopqrstuvwxyz', key=text.count)\n",
    "# >>> 'l'\n",
    "# 带入key函数，返回各个字符在'Hello World'中出现的次数，出现次数最多的字符为'l',因此输出'l'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "####  计算Python字符串中某个字符的出现次数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "5\n"
     ]
    }
   ],
   "source": [
    "#T  h  e     M  i  s  s  i  s  s  i  p  p  i     R  i  v  e  r\n",
    "#[1, 1, 2, 2, 1, 5, 4, 4, 5, 4, 4, 5, 2, 2, 5, 2, 1, 5, 1, 2, 1]\n",
    "sentence='The Mississippi River'\n",
    "\n",
    "def count_chars(s):\n",
    "        s=s.lower()\n",
    "        count=list(map(s.count,s))\n",
    "        return (max(count))\n",
    "\n",
    "print(count_chars(sentence))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.6"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
